#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "myreadline.h"


int writeAll(int fd, const char* msg, size_t len) {
    int offset = 0;
    while (len>0) {
        int res = write(fd, msg + offset, len);
        if (res<0) {
            return res;
        }
        offset += res;
        len -= res;
    }
    return 0;
}

int main() {
    MY* in = myrl_fromfd(0);
    MY* out = myrl_fromfd(1);
    char buf[BUF_SIZE];
    RES res = myrl_readline(in, buf, BUF_SIZE);
    while (MYRL_RES(res)>0 || (MYRL_RES(res)==-1 && MYRL_ERR(res)==1)) {
        if (res==0) writeAll(2, "here\n",5);
        if (!(MYRL_RES(res) == -1 && MYRL_ERR(res) == 1)) {
            int err = 0;
            if ((err = myrl_writeline(out, buf, MYRL_RES(res)))>=0) {
                err = myrl_writeline(out, buf, MYRL_RES(res));
            }
            if (err < 0) {
                writeAll(2, "Output error", 12);
                exit(1);
            }
        }
        res = myrl_readline(in, buf, BUF_SIZE);
    }
    if (MYRL_RES(res)==-1 && MYRL_ERR(res) == -1) {
        writeAll(2, "Input error", 11);
        exit(1);
    }
}
